package com.ybt.pub;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.ybt.configration.IYBTConfigration;
import com.ybt.configration.YBTConfigration;

public class ObjectSerializationUtil {
    public static byte[] toByte(Object o) throws IOException {
        if (o instanceof String) {
            String value = (String) o;
            return value.getBytes(YBTConfigration.getInstance().getProperty(
                    IYBTConfigration.DEFAULT_MIDPLAT_CHARSET));
        }
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(result);
        // 序列化对象
        out.writeObject(o);
        out.close();
        return result.toByteArray();
    }

    public static Object toObject(byte[] o) throws IOException {
        if (!isSerialization(o)) {
            return new String(o, YBTConfigration.getInstance().getProperty(
                    IYBTConfigration.DEFAULT_MIDPLAT_CHARSET));
        }
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(result);
        // 序列化对象
        out.writeObject(o);
        out.close();
        return result.toByteArray();
    }

    public static boolean isSerialization(byte[] o) {
        if (o.length < 2)
            return false;
        else
            return (o[0] & 0xAE) == 0xAE && (o[1] & 0xED) == 0xED;
    }
}
